<template>
  <div class="camera-algorithm-page">
    <!-- 算法详细配置页面 -->
    <ConfigAlgo
      v-if="showConfigPage"
      :data="currentAlgoConfig"
      :deviceId="selectedChannel?.deviceId"
      :channelId="selectedChannel?.channelId"
      @cancel="cancelConfig"
    />

    <!-- 算法配置页面 -->
    <div v-else class="page">
      <div class="content">
        <!-- 通道列表 -->
        <div class="list-section">
          <div class="section-header">
            <h3>通道列表</h3>
          </div>
          <div class="section-content" v-loading="channelLoading">
            <div class="table-header">
              <span class="col-name">通道名称</span>
              <span class="col-device">设备名称</span>
              <span class="col-status">状态</span>
            </div>
            <div class="table-body">
              <div
                v-for="channel in channelList"
                :key="channel.channelId"
                class="table-row"
                :class="{ active: selectedChannel?.channelId === channel.channelId }"
                @click="selectChannel(channel)"
              >
                <span class="col-name">{{ channel.customChannelName || channel.name }}</span>
                <span class="col-device">{{ channel.deviceName || channel.deviceId }}</span>
                <span class="col-status">
                  <span class="status-dot" :class="{ online: channel.onLine }"></span>
                </span>
              </div>
            </div>
            <div class="pagination">
              <span>{{ channelCurrentPage }}/{{ Math.ceil(channelTotalCount / 10) || 1 }}</span>
            </div>
          </div>
        </div>

        <!-- 模型列表 -->
        <div class="list-section">
          <div class="section-header">
            <h3>模型列表</h3>
          </div>
          <div class="section-content" v-loading="modelLoading">
            <div class="table-header">
              <span class="col-check">启用</span>
              <span class="col-name">模型名称</span>
            </div>
            <div class="table-body">
              <div
                v-for="model in modelList"
                :key="model.modelId"
                class="table-row"
                :class="{ active: selectedModel?.modelId === model.modelId }"
                @click="selectModel(model)"
              >
                <span class="col-check">
                  <el-checkbox v-model="model.checked" @change="onModelCheckChange(model, $event)" />
                </span>
                <span class="col-name">{{ model.modelName }}</span>
              </div>
            </div>
            <div class="pagination">
              <span>{{ modelCurrentPage }}/{{ Math.ceil(modelTotalCount / 10) || 1 }}</span>
            </div>
          </div>
        </div>

        <!-- 算法列表 -->
        <div class="list-section">
          <div class="section-header">
            <h3>算法列表</h3>
          </div>
          <div class="section-content" v-loading="algoLoading">
            <div class="table-header">
              <span class="col-check">启用</span>
              <span class="col-name">算法名称</span>
              <span class="col-action">操作</span>
            </div>
            <div class="table-body">
              <div
                v-for="algo in algorithmList"
                :key="algo.algoId"
                class="table-row"
                :class="{ active: selectedAlgorithm?.algoId === algo.algoId }"
                @click="selectAlgorithm(algo)"
              >
                <span class="col-check">
                  <el-checkbox v-model="algo.checked" :disabled="!selectedModel?.checked" />
                </span>
                <span class="col-name">{{ algo.algoName }}</span>
                <span class="col-action">
                  <el-button type="primary" size="small" @click.stop="configAlgorithm(algo)" :disabled="!algo.checked">
                    配置
                  </el-button>
                </span>
              </div>
            </div>
            <div class="option-bar">
              <el-button type="primary" @click="saveChannelAlgo" :disabled="!channelList.length || !selectedChannel?.onLine">
                保存
              </el-button>
            </div>
            <div class="pagination">
              <span>{{ algoCurrentPage }}/{{ Math.ceil(algoTotalCount / 10) || 1 }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue"
import { ElMessage } from 'element-plus'
import { deviceController, modelController, channelController } from '@/services/cameraApi'
import ConfigAlgo from '@/components/ConfigAlgo.vue'

// 响应式数据
const channelLoading = ref(false)
const modelLoading = ref(false)
const algoLoading = ref(false)

const channelList = ref([])
const modelList = ref([])
const algorithmList = ref([])

const selectedChannel = ref(null)
const selectedModel = ref(null)
const selectedAlgorithm = ref(null)

// 分页数据
const channelCurrentPage = ref(1)
const modelCurrentPage = ref(1)
const algoCurrentPage = ref(1)
const channelTotalCount = ref(0)
const modelTotalCount = ref(0)
const algoTotalCount = ref(0)

// 配置页面相关
const showConfigPage = ref(false)
const currentAlgoConfig = ref(null)

// 默认的算法配置
const defaultAlgoConfig = {
  alarmLevel: 1,
  algoStrategy: 0,
  analysisInterval: 0,
  analysisRegion: [],
  analysisValue: [],
  detectInterval: 0,
  detectRegion: [],
  strategyValue: 5,
  uploadVideo: 0,
  score: 0.5,
  alarmPeriod: 30
}

// 选择通道 - 参考bukongqiu的onChannelChange实现
const selectChannel = async (channel) => {
  if (channel.channelId === selectedChannel.value?.channelId) {
    return
  }

  selectedChannel.value = channel
  selectedModel.value = null
  selectedAlgorithm.value = null
  algorithmList.value = []

  // 重置所有模型和算法的选中状态
  cancelModelCheck()

  // 获取通道的算法配置
  await getChannelAlgo({ deviceId: channel.deviceId, channelId: channel.channelId })
}

// 选择模型 - 参考bukongqiu的onModelChange实现
const selectModel = (model) => {
  if (model && selectedModel.value?.modelId === model.modelId) {
    return
  }

  if (model) {
    selectedModel.value = model
    selectedAlgorithm.value = null
    algorithmList.value = model.algos || [];
    algoTotalCount.value = algorithmList.value.length

    // 如果有算法被选中，自动选中第一个选中的算法
    const checkedAlgo = model.algos?.find(algo => algo.checked)
    if (checkedAlgo) {
      selectedAlgorithm.value = checkedAlgo
    }
  } else {
    selectedModel.value = null
    selectedAlgorithm.value = null
    algorithmList.value = []
    algoTotalCount.value = 0
  }
}

// 选择算法
const selectAlgorithm = (algorithm) => {
  selectedAlgorithm.value = algorithm
}

// 模型复选框变化 - 参考bukongqiu的onModelCheckChange实现
const onModelCheckChange = (model, checked) => {
  model.checked = checked
  if (!checked) {
    // 如果取消选中模型，则取消选中所有算法
    (model.algos || []).forEach(algo => {
      algo.checked = false;
    })

    // 如果当前选中的模型被取消选中，更新算法列表显示
    if (selectedModel.value?.modelId === model.modelId) {
      algorithmList.value.forEach(algo => {
        algo.checked = false
      })
    }
  }
}

// 取消模型和算法的选中状态 - 参考bukongqiu的实现
const cancelModelCheck = () => {
  const config = { 0: 5, 1: 10, 2: 1 };
  for (const model of modelList.value) {
    model.checked = false;
    const { algos } = model
    if (Array.isArray(algos)) {
      for (const algo of algos) {
        Object.assign(algo, defaultAlgoConfig);
        algo.checked = false
        algo.strategyValue = config[algo.algoStrategy] || 5
      }
    }
  }
}

// 获取通道算法配置 - 参考bukongqiu的getChannelAlgo实现
const getChannelAlgo = async (params) => {
  try {
    algoLoading.value = true

    const response = await channelController.getChannelAlgo(params)

    // 处理不同的响应格式
    let configModels = []
    if (response.models) {
      // bukongqiu格式: { models: [...] }
      configModels = response.models
    } else if (response.data && response.data.models) {
      // 当前项目格式: { data: { models: [...] } }
      configModels = response.data.models
    } else if (Array.isArray(response.data)) {
      // 直接数组格式: { data: [...] }
      configModels = response.data
    }

    if (Array.isArray(configModels) && configModels.length > 0) {
      let checkedModel = null;

      // 遍历所有模型，根据后端返回的配置数据设置选中状态
      modelList.value.forEach(item => {
        const model = configModels.find(model => model.modelId === item.modelId);
        if (model) {
          // 设置模型为选中状态
          item.checked = true
          if (checkedModel === null) {
            checkedModel = item
          }

          // 处理模型下的算法配置
          const { algos } = model;
          if (Array.isArray(algos) && Array.isArray(item.algos)) {
            item.algos.forEach(ele => {
              const algo = algos.find(algo => algo.algoId === ele.algoId);
              if (algo) {
                // 移除算法名称相关的属性，避免冲突
                Object.keys(algo).forEach(key => key.startsWith("algoName") && Reflect.deleteProperty(algo, key))
                // 将后端配置数据合并到算法对象中
                Object.assign(ele, algo)
                ele.checked = true
              } else {
                ele.checked = false
              }
            })
          }
        } else {
          // 如果模型没有配置，设置为未选中
          item.checked = false
        }
      });

      // 自动选中第一个已配置的模型，如果没有则选中第一个模型
      if (checkedModel) {
        selectModel(checkedModel)
      } else if (modelList.value.length > 0) {
        selectModel(modelList.value[0])
      }
    } else {
      // 如果没有配置数据，重置所有选中状态
      cancelModelCheck()
      if (modelList.value.length > 0) {
        selectModel(modelList.value[0])
      }
    }
  } catch (error) {
    // 如果获取失败，重置所有选中状态
    cancelModelCheck()
    if (modelList.value.length > 0) {
      selectModel(modelList.value[0])
    }
    ElMessage.error('获取通道算法配置失败: ' + (error.message || error))
  } finally {
    algoLoading.value = false
  }
}

// 保存通道算法配置 - 参考bukongqiu的modifyCameraData实现
const saveChannelAlgo = async () => {
  if (!selectedChannel.value) {
    ElMessage.warning('请先选择通道')
    return
  }

  if (!selectedChannel.value.onLine) {
    ElMessage.warning('通道不在线时不能启用模型')
    return
  }

  try {
    algoLoading.value = true

    // 构建保存参数 - 只保存选中的模型和算法
    const models = modelList.value.filter(m => m.checked).map(m => ({
      modelId: m.modelId,
      algos: (m.algos || []).filter(a => a.checked).map(a => ({
        ...a,
        algoName: a.algoName
      }))
    }))

    const params = {
      deviceId: selectedChannel.value.deviceId,
      channelId: selectedChannel.value.channelId,
      models: models
    }

    await channelController.setChannelAlgo(params)

    // 重新获取配置
    await getChannelAlgo({
      deviceId: selectedChannel.value.deviceId,
      channelId: selectedChannel.value.channelId
    })

    ElMessage.success('更新成功')
  } catch (error) {
    ElMessage.error(error?.msg || error || '保存失败')
  } finally {
    algoLoading.value = false
  }
}

// 配置算法
const configAlgorithm = async (algorithm) => {
  if (!selectedChannel.value) {
    ElMessage.warning('请先选择通道')
    return
  }

  try {
    // 获取当前算法配置
    const { data } = await channelController.getChannelAlgo({
      deviceId: selectedChannel.value.deviceId,
      channelId: selectedChannel.value.channelId,
      algoId: algorithm.algoId
    })

    // 合并算法信息和配置数据
    currentAlgoConfig.value = {
      ...defaultAlgoConfig,
      ...data,
      algoId: algorithm.algoId,
      algoName: algorithm.algoName,
      algoNameEn: algorithm.algoNameEn || algorithm.algoName
    }

    showConfigPage.value = true
  } catch (error) {
    // 如果获取失败，使用默认配置
    currentAlgoConfig.value = {
      ...defaultAlgoConfig,
      algoId: algorithm.algoId,
      algoName: algorithm.algoName,
      algoNameEn: algorithm.algoNameEn || algorithm.algoName
    }
    showConfigPage.value = true
  }
}

// 取消配置
const cancelConfig = () => {
  showConfigPage.value = false
  currentAlgoConfig.value = null
}



// 获取设备列表
const getDeviceList = async () => {
  const { data } = await deviceController.getDeviceList({
    pageNum: 1,
    showNums: 1000
  })
  return data?.list || []
}

// 获取通道列表 - 参考bukongqiu的getDeviceChannel实现
const getChannelList = async () => {
  try {
    channelLoading.value = true

    // 先获取设备列表
    const devices = await getDeviceList()
    const allChannels = []

    // 为每个设备获取通道列表
    for (const device of devices) {
      try {
        const channels = await getChannels(device.deviceId, device.customDeviceName || device.name)
        allChannels.push(...channels)
      } catch (error) {
      }
    }

    channelList.value = allChannels
    channelTotalCount.value = allChannels.length
  } catch (error) {
    ElMessage.error(error || '获取通道列表失败')
    channelList.value = []
  } finally {
    channelLoading.value = false
  }
}

// 获取单个设备的通道列表 - 参考bukongqiu的getChannels实现
const getChannels = async (deviceId, deviceName) => {
  const { data } = await deviceController.getChannelList({
    page: 1,
    count: 1000,
    deviceId
  })
  if (data?.list && Array.isArray(data.list)) {
    return data.list.map(e => ({
      ...e,
      deviceName: deviceName,
      deviceId
    }))
  } else {
    return []
  }
}



// 初始化数据 - 参考bukongqiu的getData实现
const initializeData = async () => {
  try {
    algoLoading.value = true

    // 1. 获取通道列表（包含设备列表和通道列表）
    await getChannelList()

    // 2. 获取模型列表
    await getModelListData()

    // 3. 如果有通道和模型，自动选择第一个通道
    if (channelList.value.length > 0 && modelList.value.length > 0) {
      // 使用nextTick确保DOM更新后再选择通道
      await new Promise(resolve => setTimeout(resolve, 100))
      await selectChannel(channelList.value[0])
    }
  } catch (error) {
    ElMessage.error('初始化失败: ' + (error.message || error))
  } finally {
    algoLoading.value = false
  }
}

// 获取模型列表数据
const getModelListData = async () => {
  try {
    modelLoading.value = true
    const { data, total } = await modelController.getModel({ page: 1, count: 20 })
    modelTotalCount.value = total || 0;

    if (Array.isArray(data)) {
      modelList.value = data.map(model => ({
        ...model,
        checked: false,
        algos: model.algos ? model.algos.map(algo => ({
          ...algo,
          ...defaultAlgoConfig,
          checked: false,
          strategyValue: { 0: 5, 1: 10, 2: 1 }[algo.algoStrategy] || 5
        })) : []
      }))
      // 重置选中状态
      cancelModelCheck()
    } else {
      modelList.value = [];
    }
  } catch (error) {
    ElMessage.error('获取模型列表失败: ' + (error.message || error))
    modelList.value = []
    modelTotalCount.value = 0
  } finally {
    modelLoading.value = false
  }
}

// 初始化 - 按照 bukongqiu 的接口调用顺序
onMounted(() => {
  initializeData()
})
</script>

<style lang="scss" scoped>
.camera-algorithm-page {
  height: 100%;
  padding: 20px;

  .page {
    height: 100%;

    .content {
      display: flex;
      gap: 20px;
      height: 100%;

      .list-section {
        flex: 1;
        background: #fff;
        border-radius: 8px;
        border: 1px solid #e8e8e8;
        display: flex;
        flex-direction: column;

        .section-header {
          padding: 16px;
          border-bottom: 1px solid #e8e8e8;
          background-color: #f8f9fa;

          h3 {
            margin: 0;
            font-size: 16px;
            font-weight: 500;
            color: #333;
          }
        }

        .section-content {
          flex: 1;
          display: flex;
          flex-direction: column;

          .table-header {
            display: flex;
            padding: 12px 16px;
            background-color: #f8f9fa;
            border-bottom: 1px solid #e8e8e8;
            font-weight: 500;
            color: #666;
            font-size: 14px;

            .col-name {
              flex: 2;
            }

            .col-device {
              flex: 2;
            }

            .col-status {
              flex: 1;
              text-align: center;
            }

            .col-check {
              flex: 1;
              text-align: center;
            }

            .col-action {
              flex: 1;
              text-align: center;
            }
          }

          .table-body {
            flex: 1;
            overflow-y: auto;

            .table-row {
              display: flex;
              padding: 12px 16px;
              border-bottom: 1px solid #f0f0f0;
              cursor: pointer;
              transition: all 0.2s;
              align-items: center;

              &:hover {
                background-color: #f8f9fa;
              }

              &.active {
                background-color: #e6f7ff;
                border-color: #1890ff;
              }

              .col-name {
                flex: 2;
                font-size: 14px;
                color: #333;
              }

              .col-device {
                flex: 2;
                font-size: 14px;
                color: #666;
              }

              .col-status {
                flex: 1;
                text-align: center;

                .status-dot {
                  display: inline-block;
                  width: 8px;
                  height: 8px;
                  border-radius: 50%;
                  background-color: #ff4d4f;

                  &.online {
                    background-color: #52c41a;
                  }
                }
              }

              .col-check {
                flex: 1;
                text-align: center;
              }

              .col-action {
                flex: 1;
                text-align: center;
              }
            }
          }

          .option-bar {
            padding: 12px 16px;
            border-top: 1px solid #e8e8e8;
            text-align: right;
            background-color: #f8f9fa;
          }

          .pagination {
            padding: 12px 16px;
            border-top: 1px solid #e8e8e8;
            text-align: center;
            background-color: #f8f9fa;
            font-size: 14px;
            color: #666;
          }
        }
      }
    }
  }
}
</style>
